import random

from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from rest_framework.generics import GenericAPIView, CreateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from meiduo_mall.libs.captcha.captcha import captcha
from meiduo_mall.utils.yuntongxun.sms import CCP
from users.models import User
from verifications import constants
from verifications.constants import SMS_CODE_TEMP_ID
from verifications.serializers import ImageCodeCheckSerializer
from celery_tasks.sms import tasks as sms_tasks

class ImageCodeView(APIView):
    """
    图片验证码
    """

    def get(self, request, image_code_id):
        # 生成验证码图片
        text, image = captcha.generate_captcha()

        # 保存验证码
        redis_conn = get_redis_connection("verify_code")
        redis_conn.setex("img_%s" % image_code_id, constants.IMAGE_CODE_REDIS_EXPIRES, text)

        # 返回验证码图片
        # 固定返回验证码图片数据，不需要REST framework框架的Response帮助我们决定返回响应数据的格式
        # 所以此处直接使用Django原生的HttpResponse即可
        return HttpResponse(image, content_type="images/jpg")


# url('^sms_codes/(?P<mobile>1[3-9]\d{9})/$', views.SMSCodeView.as_view()),
class SMSCodeView(GenericAPIView):
    """
    短信验证码
    传入参数：
        mobile, image_code_id, text
    """
    serializer_class = ImageCodeCheckSerializer

    def get(self, request, mobile):

        # 创建序列化对象,并进行校验
        serializer = self.get_serializer(data = request.query_params)
        serializer.is_valid(raise_exception= True)

        # 生成短信验证码
        sms_code = "%06d" % random.randint(0, 999999)

        print(sms_code)

        # 保存短信验证码与发送记录
        radis_conn = get_redis_connection('verify_code')

        radis_pl = radis_conn.pipeline()
        radis_pl.setex("sms_%s" % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        radis_pl.setex("send_flag_%s" % mobile, constants.SEND_SMS_CODE_INTERVAL, mobile)
        radis_pl.execute()

        # 发送短信验证码
        # sms_code_expires = str(constants.SMS_CODE_REDIS_EXPIRES // 60)
        # ccp = CCP()
        # ccp.send_template_sms(mobile, [sms_code, sms_code_expires], SMS_CODE_TEMP_ID)
        sms_code_expires = str(constants.SMS_CODE_REDIS_EXPIRES // 60)
        sms_tasks.send_sms_code.delay(mobile, sms_code, sms_code_expires)

        return Response({"message": "OK"})
